<template>
  <el-input
    v-bind="$attrs"
    v-on="listeners"
    v-model="currentValue">
    <span slot="append">%</span>
  </el-input>
</template>

<script>

export default {
  name: 'CPercentInput',
  inheritAttrs: false,
  props: {
    value: {},
    fixed: {
      type: Number,
      default () {
        return 2
      }
    }
  },
  computed: {
    currentValue: {
      get () {
        const v = this.value
        if (v && !isNaN(v)) {
          return (+v).mul(100) + ''
        } else {
          return v
        }
      },
      set (v) {
        if (v && !isNaN(v)) {
          this.$emit('input', '' + (+(+v).div(100).toFixed(10)))
        } else {
          this.$emit('input', v)
        }
      }
    },
    listeners () {
      const self = this
      return Object.assign({},
        // 我们从父级添加所有的监听器
        self.$listeners,
        // 然后我们添加自定义监听器，
        // 或覆写一些监听器的行为
        {
          // 这里确保组件配合 `v-model` 的工作
          input (v) {
            self.currentValue = v
            if (!isNaN(v)) {
              const pos = v.indexOf('.')
              if (pos > -1) {
                self.$nextTick(() => {
                  self.currentValue = v.substring(0, pos + 1 + self.fixed)
                })
              }
            } else {
              self.$nextTick(() => {
                const str = v.replace(/[^0-9.-]/g, '')
                const index = str.indexOf('.')
                const num = str.replace(/\./g, '')
                if (index > 0) {
                  self.currentValue = num.substring(0, index) + '.' + num.substring(index)
                } else {
                  self.currentValue = num
                }
              })
            }
          }
        }
      )
    }
  }
}
</script>

<style></style>
